package cc.vv.baselibrary.util;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import cc.vv.baselibrary.R;
import cc.vv.baselibrary.global.BCFileBasePath;
import cc.vv.lkbasecomponent.base.app.LKBaseApplication;


/**
 * 图片下载工具
 *
 * @author sun.li
 */

public class ImgDownload {

    private static String filePath;
    private static Bitmap mBitmap;
    private static String mFileName = "BoTo";
    private static String mSaveMessage;
    private final static String TAG = "ImageActivity";
    private static Context context;

    public static void downloadImg(Context contexts, String filePaths) {
        context = contexts;
        filePath = filePaths;
        new Thread(saveFileRunnable).start();
    }

    private static Runnable saveFileRunnable = new Runnable() {
        @Override
        public void run() {
            try {
                byte[] data = getImage(filePath);
                if (data != null) {
                    mBitmap = BitmapFactory.decodeByteArray(data, 0, data.length);// bitmap
                } else {
                    Toast.makeText(context, "Image error!", Toast.LENGTH_LONG).show();
                }

                mFileName = "bt" + System.currentTimeMillis() + ".jpg";

                saveFile(mBitmap, mFileName);

            } catch (IOException e) {
                mSaveMessage = "图片保存失败！";
                LKLogUtil.e(e.getMessage(), e);
            } catch (Exception e) {
                LKLogUtil.e(e.getMessage(), e);
            }
            messageHandler.sendMessage(messageHandler.obtainMessage());
        }

    };

    private static Handler messageHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            Log.d(TAG, mSaveMessage);
            LKToastUtil.showToastShort(mSaveMessage);
        }
    };


    /**
     * Get image from newwork
     *
     * @param path The path of image
     * @return byte[]
     * @throws Exception
     */
    public static byte[] getImage(String path) throws Exception {
        URL url = new URL(path);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setConnectTimeout(5 * 1000);
        conn.setRequestMethod("GET");
        InputStream inStream = conn.getInputStream();
        if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
            return readStream(inStream);
        }
        return null;
    }

    /**
     * Get data from stream
     *
     * @param inStream
     * @return byte[]
     * @throws Exception
     */
    public static byte[] readStream(InputStream inStream) throws Exception {
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = 0;
        while ((len = inStream.read(buffer)) != -1) {
            outStream.write(buffer, 0, len);
        }
        outStream.close();
        inStream.close();
        return outStream.toByteArray();
    }


    /**
     * 保存文件
     *
     * @param bm
     * @param fileName
     * @throws IOException
     */
    public static void saveFile(Bitmap bm, String fileName) throws IOException {
        BufferedOutputStream bos = null;
        FileOutputStream fileOutputStream = null;
        try {
            File path_1 = new File(BCFileBasePath.PATH_LOAD);
            if (!path_1.exists()) {   //判断文件夹是否存在，不存在则创建
                path_1.mkdirs();
            }
            File path_2 = new File(BCFileBasePath.PATH_CACHE_IMG_LOAD);
            if (!path_2.exists()) {   //判断文件夹是否存在，不存在则创建
                path_2.mkdirs();
            }
            if (TextUtils.isEmpty(fileName)) {
                fileName = System.currentTimeMillis() + ".jpg";
            }
            String filePath = path_2 + "/" + fileName;
//            mSaveMessage = "图片已保存至" + path_3 + "文件夹";
            File myCaptureFile = new File(filePath);
            fileOutputStream = new FileOutputStream(myCaptureFile);
            bos = new BufferedOutputStream(fileOutputStream);
            bm.compress(Bitmap.CompressFormat.JPEG, 80, bos);
            if (context == null) {
                context = LKBaseApplication.getApplication();
            }
            if (null != context) {
                mSaveMessage = context.getString(R.string.img_save_locally_prompt);
                // 其次把文件插入到系统图库
                try {
                    MediaStore.Images.Media.insertImage(context.getContentResolver(), filePath, fileName, null);
                } catch (FileNotFoundException e) {
                    LKLogUtil.e(e.getMessage(), e);
                }
                // 最后通知图库更新
                context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + filePath)));
            }
        } catch (FileNotFoundException e) {
            LKLogUtil.e(e.getMessage(), e);
        } finally {
            if (null != bos) {
                bos.flush();
                bos.close();
            }
            if (null != fileOutputStream) {
                fileOutputStream.flush();
                fileOutputStream.close();
            }
        }
    }
}
